#!/bin/bash

# $Header: /opt/unixmon/tools/DNS/RCS/sync-zone,v 1.1 2012/11/27 07:50:51 yajin Exp $

# Author: yang.jin@ebay.com
# this script synchronizes a master zone from the primary DNS master to the secondary masters

export PATH=/bin:/usr/bin

NAMED_CHECKZONE="/opt/bind/sbin/named-checkzone"
RNDC="/opt/bind/sbin/rndc"
ZONECAT="/usr/local/sbin/zonecat -T"
ISPRI="/usr/local/sbin/is_primaster"
RSYNC="/usr/local/bin/rsync"
SSH=/bin/ssh

MASTER_ZONE_FILES="/etc/named/its.zones"
ZONE_ROOT_DIR="/var/named/db"
DNS_SERVERS_LIST="/etc/named/IT_DNS_SERVERS"

print_usage ()
{
echo "Usage: 
	$(basename $0) zonename" >&2

}

if [ $# -ne 1 ]; then print_usage; exit 1; fi 

if [ ! -f $DNS_SERVERS_LIST ]; then
        echo -e "Error: configuration file \"$DNS_SERVERS_LIST\" does not exist." >&2
        exit 2
fi

. $DNS_SERVERS_LIST

if [ ! -x $ISPRI ]; then
	echo "Error: $ISPRI does not exist, or, is not executable." >&2
	exit 1
fi

$ISPRI
if [ $? -ne 0 ]; then 
	echo "Error: this host is not the primary DNS master."  >&2
	exit 1
fi

zone=$1

tmp=$($ZONECAT $MASTER_ZONE_FILES  | grep "^${zone}[ \t]\{1,\}") 
if [ $? -ne 0 ]; then
	echo -e "Error: Zone \"${zone}\" cannot be found on $MASTER_ZONE_FILES.\n" >&2
	print_usage
	exit 1
fi

# echo "$tmp" | read -r zonename type masters file
type=$(echo $tmp | awk '{print $2}')
file=$(echo $tmp | awk '{print $4}')

if [ "X${type}" != "Xmaster" ]; then
	echo -e "Error: Zone \"${zone}\" isn't a master zone.\n" >&2
	exit 1
fi

if [ ! -f ${ZONE_ROOT_DIR}/${file} ]; then
	echo -e "Error: Zone file \"${ZONE_ROOT_DIR}/${file}\" for the zone \"$zone\" doesn't exist.\n" >&2
	exit 1
fi

echo -e "\nVerifying zone \"$zone\" and its zone file ${ZONE_ROOT_DIR}/${file}...\t\c" 
if ! $NAMED_CHECKZONE $zone ${ZONE_ROOT_DIR}/${file} >/dev/null; then exit 1; fi
echo -e "Passed.\n"

for h in $DNS_PSEUDO_MASTERS; do
	echo -e "Synchronizing ${ZONE_ROOT_DIR}/${file} to ${h}:$(dirname ${ZONE_ROOT_DIR}/${file})...\t\c"
	$RSYNC ${ZONE_ROOT_DIR}/${file} ${h}:$(dirname ${ZONE_ROOT_DIR}/${file})
	echo "Done."
	echo -e "Reloading zone \"$zone\" on $h...\t\t\c"
	ssh $h "$RNDC reload $zone"
	echo
done
